package logic.util;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.shwread.android.qysw10000204.R;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import logic.constants.DefaultConsts;
import logic.util.logutil.LogUtil;


/**
 * 图片工具类
 * 
 * @author 刘宾
 * @date 2014年6月30日 上午10:42:18
 */
public class ImageUtil
{
	private static final String IMAGE_HEAD = "file://";
	
	/** 加载网络url */
	public static void loadWebUrl(String imgUrl, ImageView imageView) {
		ImageLoader.getInstance().displayImage(imgUrl, imageView);
	}
	
	/** 加载网络url */
	public static void loadWebUrl(String imgUrl, ImageView imageView, ImageLoadingListener listener) {
		ImageLoader.getInstance().displayImage(imgUrl, imageView, listener);
	}
	
	/** 下载图片 */
	public static void downImage(final String url, final String path, final String ilename, final Context context) {
		final String filename = new Md5FileNameGenerator().generate(url) + ".PNG";
		if (new File(url + filename).exists())
		{
			Toast.makeText(context, "保存成功,路径：" + path + filename, Toast.LENGTH_LONG).show();
		}
		else
		{
			ImageLoader.getInstance().loadImage(url, new SimpleImageLoadingListener()
			{
				@Override
				public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
					super.onLoadingComplete(imageUri, view, loadedImage);
					Thread thread = new Thread(new Runnable()
					{
						
						@Override
						public void run() {
							saveBitmap(loadedImage, path, filename);
							scanPhotos(path + filename, context);
						}
						
					});
					thread.start();
					Toast.makeText(context, "保存成功,路径：" + path + filename, Toast.LENGTH_LONG).show();
				}
			});
		}
	}
	
	public static void scanPhotos(String filePath, Context context) {
		Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		Uri uri = Uri.fromFile(new File(filePath));
		intent.setData(uri);
		context.sendBroadcast(intent);
	}
	
	/**
	 * 初始化一个最低的配置
	 */
	public static void initImageLoader_low(Context context) {
		System.out.println("ImageUtil --> init low ImageLoader config");
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().tasksProcessingOrder(QueueProcessingType.LIFO).threadPoolSize(3).defaultDisplayImageOptions(low_options).memoryCacheSizePercentage(10).writeDebugLogs().build();
		ImageLoader.getInstance().init(config);
	}
	
	/**
	 * 初始化一个正常的配置
	 */
	public static void initImageLoader_normal(Context context) {
		System.out.println("ImageUtil --> init normal ImageLoader config");
		ImageLoaderConfiguration config = null;
		try
		{
			config = new ImageLoaderConfiguration.Builder(context).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().tasksProcessingOrder(QueueProcessingType.LIFO).threadPoolSize(5).defaultDisplayImageOptions(normal_options).diskCache(new LruDiscCache(SDcardUtil.getImagePath(), new Md5FileNameGenerator(), 0)).memoryCacheSizePercentage(60).writeDebugLogs().build();
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ImageLoader.getInstance().init(config);
	}
	
	private final static DisplayImageOptions low_options    = new DisplayImageOptions.Builder().bitmapConfig(Bitmap.Config.RGB_565).showImageOnLoading(R.drawable.bookcover_default).showImageForEmptyUri(R.drawable.bookcover_default).showImageOnFail(R.drawable.bookcover_default).imageScaleType(ImageScaleType.EXACTLY).cacheOnDisk(false).cacheInMemory(true).build();
	private final static DisplayImageOptions normal_options = new DisplayImageOptions.Builder().bitmapConfig(Bitmap.Config.RGB_565).showImageOnLoading(R.drawable.bookcover_default).showImageForEmptyUri(R.drawable.bookcover_default).showImageOnFail(R.drawable.bookcover_default).cacheOnDisk(true).cacheInMemory(true).build();
	
	/** 加载本地url */
	public static void loadLocalUrl(String imgUrl, ImageView imageView) {
		ImageLoader.getInstance().displayImage(IMAGE_HEAD + imgUrl, imageView, low_options);
	}
	
	public static void loadLocalUrl(String imgUrl, ImageView imageView, DisplayImageOptions options) {
		ImageLoader.getInstance().displayImage(IMAGE_HEAD + imgUrl, imageView, options);
	}
	
	/**
	 * 如果需要重新配置ImageLoader，需要调用此方法清理配置
	 */
	public static void destroyImageLoader() {
		try
		{
			System.out.println("ImageUtil --> destroy ImageLoader config");
			ImageLoader.getInstance().destroy();
		}
		catch (Exception e)
		{
			System.err.println("ImageUtil --> destroy ImageLoader config");
			e.printStackTrace();
		}
	}
	
	/**
	 * 加载本地图片
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getLoacalBitmap(String url) {
		try
		{
			FileInputStream fis = new FileInputStream(url);
			return BitmapFactory.decodeStream(fis); // 把流转化为Bitmap图片
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	/** uri转换为Bitmap */
	public static Bitmap uriToBitmap(Context context, Uri imageUri) {
		try
		{
			return MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageUri);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 通过压缩图片的尺寸来压缩图片大小
	 * 
	 * @param pathName
	 *            图片的完整路径
	 * @param targetWidth
	 *            缩放的目标宽度
	 * @param targetHeight
	 *            缩放的目标高度
	 * @return 缩放后的图片
	 */
	public static Bitmap compressBySize(String pathName, int targetWidth, int targetHeight) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
		Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
		// 得到图片的宽度、高度；
		int imgWidth = opts.outWidth;
		int imgHeight = opts.outHeight;
		// 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
		int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
		int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
		if (widthRatio > 1 || widthRatio > 1)
		{
			if (widthRatio > heightRatio)
			{
				opts.inSampleSize = widthRatio;
			}
			else
			{
				opts.inSampleSize = heightRatio;
			}
		}
		// 设置好缩放比例后，加载图片进内容；
		opts.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeFile(pathName, opts);
		return bitmap;
	}
	
	/**
	 * 等比例缩放图片
	 * 
	 * @param pathString
	 *            文件路径
	 * @param dstMaxWH
	 *            目标文件宽高最大值
	 */
	public static Bitmap scaleImageByPath(String pathString, int dstMaxWH) {
		Bitmap retBm = null;
		// 路径为空
		if (TextUtils.isEmpty(pathString) || dstMaxWH <= 0) { return retBm; }
		File file = new File(pathString);
		if (!file.exists()) { return retBm; }
		
		try
		{
			// 打开源文件
			Bitmap srcBitmap;
			{
				java.io.InputStream is;
				is = new FileInputStream(pathString);
				BitmapFactory.Options opts = getOptionsWithInSampleSize(pathString, dstMaxWH);
				srcBitmap = BitmapFactory.decodeStream(is, null, opts);
				if (srcBitmap == null) return retBm;
			}
			// 原图片宽高
			int width = srcBitmap.getWidth();
			int height = srcBitmap.getHeight();
			// 获得缩放因子
			float scale = 1.f;
			{
				if (width > dstMaxWH || height > dstMaxWH)
				{
					float scaleTemp = (float) dstMaxWH / (float) width;
					float scaleTemp2 = (float) dstMaxWH / (float) height;
					if (scaleTemp > scaleTemp2) scale = scaleTemp2;
					else scale = scaleTemp;
				}
			}
			// 图片缩放
			Bitmap dstBitmap;
			if (scale == 1.f) dstBitmap = srcBitmap;
			else
			{
				Matrix matrix = new Matrix();
				matrix.postScale(scale, scale);
				dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, width, height, matrix, true);
				if (!srcBitmap.isRecycled()) srcBitmap.recycle();
				srcBitmap = null;
			}
			
			retBm = dstBitmap;
		}
		catch (Exception e)
		{
			return retBm;
		}
		return retBm;
	}
	
	/**
	 * 通过压缩图片的尺寸来压缩图片大小
	 * 
	 * @param bitmap
	 *            要压缩图片
	 * @param targetWidth
	 *            缩放的目标宽度
	 * @param targetHeight
	 *            缩放的目标高度
	 * @return 缩放后的图片
	 */
	public static Bitmap compressBySize(Bitmap bitmap, int targetWidth, int targetHeight) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 100, baos);
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, opts);
		// 得到图片的宽度、高度；
		int imgWidth = opts.outWidth;
		int imgHeight = opts.outHeight;
		
		LogUtil.d(DefaultConsts.TAG, "压缩前图片尺寸：width:" + imgWidth + ",height:" + imgHeight);
		
		// 分别计算图片宽度、高度与目标宽度、高度的比例；取大于该比例的最小整数；
		int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
		int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
		if (widthRatio > 1 && widthRatio > 1)
		{
			if (widthRatio > heightRatio)
			{
				opts.inSampleSize = widthRatio;
			}
			else
			{
				opts.inSampleSize = heightRatio;
			}
		}
		// 设置好缩放比例后，加载图片进内存；
		opts.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length, opts);
		LogUtil.d(DefaultConsts.TAG, "压缩后图片：width:" + opts.outWidth + ",height:" + opts.outHeight);
		return bitmap;
	}
	
	/**
	 * 通过压缩图片的尺寸来压缩图片大小，通过读入流的方式，可以有效防止网络图片数据流形成位图对象时内存过大的问题；
	 * 
	 * @param is
	 *            要压缩图片，以流的形式传入
	 * @param targetWidth
	 *            缩放的目标宽度
	 * @param targetHeight
	 *            缩放的目标高度
	 * @return 缩放后的图片
	 * @throws IOException
	 *             读输入流的时候发生异常
	 */
	public static Bitmap compressBySize(InputStream is, int targetWidth, int targetHeight) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buff = new byte[1024];
		int len = 0;
		while ((len = is.read(buff)) != -1)
		{
			baos.write(buff, 0, len);
		}
		
		byte[] data = baos.toByteArray();
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
		// 得到图片的宽度、高度；
		int imgWidth = opts.outWidth;
		int imgHeight = opts.outHeight;
		// 分别计算图片宽度、高度与目标宽度、高度的比例；取大于该比例的最小整数；
		int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
		int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
		if (widthRatio > 1 && widthRatio > 1)
		{
			if (widthRatio > heightRatio)
			{
				opts.inSampleSize = widthRatio;
			}
			else
			{
				opts.inSampleSize = heightRatio;
			}
		}
		// 设置好缩放比例后，加载图片进内存；
		opts.inJustDecodeBounds = false;
		bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
		return bitmap;
	}
	
	/**
	 * 通过降低图片的质量来压缩图片
	 * 
	 * @param bitmap
	 *            要压缩的图片
	 * @param maxSize
	 *            压缩后图片大小的最大值,单位KB
	 * @return 压缩后的图片
	 */
	public static Bitmap compressByQuality(Bitmap bitmap, int maxSize) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int quality = 90;
		bitmap.compress(CompressFormat.JPEG, quality, baos);
		LogUtil.d(DefaultConsts.TAG, "图片压缩前大小：" + baos.toByteArray().length + "byte");
		while (baos.toByteArray().length / 1024 > maxSize)
		{
			quality -= 10;
			baos.reset();
			bitmap.compress(CompressFormat.JPEG, quality, baos);
			LogUtil.d(DefaultConsts.TAG, "质量压缩到原来的" + quality + "%时大小为：" + baos.toByteArray().length + "byte");
		}
		LogUtil.d(DefaultConsts.TAG, "图片压缩后大小：" + baos.toByteArray().length + "byte");
		bitmap = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);
		return bitmap;
	}
	
	/**
	 * Bitmap 转换为 InputStream
	 */
	public static InputStream Bitmap2IS(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		InputStream sbs = new ByteArrayInputStream(baos.toByteArray());
		return sbs;
	}
	
	/**
	 * 获取文件写入路径，无视错误
	 * 
	 * @param fileName
	 *            文件全名
	 * @return 返回路径，返回null则拒绝写入操作
	 */
	public static String getWritePathIgnoreError(String fileName) {
		try
		{
			MultiCardFilePath path = MultiCard.getInstance().getWritePath(fileName);
			return path.getFilePath();
		}
		catch (LimitSpaceUnwriteException e)
		{
			Log.d("dzp", "内存不足");
			e.printStackTrace();
		}
		catch (IllegalArgumentException e)
		{
			Log.d("dzp", "文件名有误:" + fileName);
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 是否需要缩放图片 1.图片尺寸大于200k 2.图片大小大于屏幕最宽
	 */
	public static Boolean isNeedScaleImage(String filename) {
		// 判断文件大小
		File imageFile = new File(filename);
		if (!imageFile.exists()) { return false; }
		if (imageFile.length() > 200 * 1024) { return true; }
		
		// 判断文件尺寸
		Options bitmapOptions = new Options();
		bitmapOptions.inJustDecodeBounds = true;// 只取得outHeight(图片原始高度)和
		bitmapOptions.inSampleSize = 1;
		// outWidth(图片的原始宽度)而不加载图片
		Bitmap bitmap = BitmapFactory.decodeFile(filename, bitmapOptions);
		if (bitmap == null) { return false; }
		if (bitmap.getWidth() > ScreenUtil.screenMin || bitmap.getHeight() > ScreenUtil.screenMin)
		{
			if (!bitmap.isRecycled())
			{
				bitmap.recycle();
				bitmap = null;
			}
			return true;
		}
		return false;
	}
	
	/**
	 * 压缩图片：用于拍照后
	 * 
	 * @param context
	 * @param imageFile
	 */
	public static void scaleImage(Context context, File imageFile) {
		if (isNeedScaleImage(imageFile.getAbsolutePath()))
		{// 如果图片超过200K，则进行压缩
		 // 图片处理
			String tempPath = getWritePathIgnoreError("O_temp.jpg");
			File fileTemp = new File(tempPath);
			if (fileTemp.exists())
			{
				fileTemp.delete();
			}
			scaleImageWithFilter(imageFile, fileTemp, ScreenUtil.screenMin, true, true, true);
			// 删除原来图片，把临时文件改为目标文件
			imageFile.delete();
			fileTemp.renameTo(imageFile);
		}
	}
	
	/**
	 * 等比例缩放图片（带滤波器）
	 * 
	 * @param srcFile
	 *            来源文件
	 * @param dstFile
	 *            目标文件
	 * @param dstMaxWH
	 *            目标文件宽高最大值
	 * @param bContrast
	 *            提高对比度滤波器，可使图片变亮丽
	 * @param bSharp
	 *            锐化图片，可使图片清晰（暂时无效果）
	 * @param bRotate
	 *            是否旋转
	 */
	public static Boolean scaleImageWithFilter(File srcFile, File dstFile, int dstMaxWH, Boolean bContrast, Boolean bSharp, Boolean bRotate) {
		Boolean bRet = false;
		
		// 路径文件不存在
		if (!srcFile.exists()) { return bRet; }
		
		try
		{
			// 判断是否旋转
			float rotate = 90.0F;
			if (bRotate)
			{
				ExifInterface localExifInterface = new ExifInterface(srcFile.getAbsolutePath());
				int rotateInt = localExifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
				// LectekLog.i("gzb", "CommonUtil scaleImageWithFilter Orientation=" + rotateInt + ";rotate=" +
				// getImageRotate(rotateInt));
				rotate = getImageRotate(rotateInt);
			}
			
			// 打开源文件
			Bitmap srcBitmap;
			{
				java.io.InputStream is;
				is = new FileInputStream(srcFile);
				BitmapFactory.Options opts = getOptionsWithInSampleSize(srcFile.getPath(), dstMaxWH);
				srcBitmap = BitmapFactory.decodeStream(is, null, opts);
				if (srcBitmap == null) return bRet;
			}
			// 原图片宽高
			int width = srcBitmap.getWidth();
			int height = srcBitmap.getHeight();
			// 获得缩放因子
			float scale = 1.f;
			{
				if (width > dstMaxWH || height > dstMaxWH)
				{
					float scaleTemp = (float) dstMaxWH / (float) width;
					float scaleTemp2 = (float) dstMaxWH / (float) height;
					if (scaleTemp > scaleTemp2) scale = scaleTemp2;
					else scale = scaleTemp;
				}
			}
			// 图片缩放
			Bitmap dstBitmap;
			if (scale == 1.f) dstBitmap = srcBitmap;
			else
			{
				Matrix matrix = new Matrix();
				matrix.postScale(scale, scale);
				if (bRotate)
				{
					matrix.postRotate(rotate);
				}
				
				dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, width, height, matrix, true);
				
				if (!srcBitmap.isRecycled()) srcBitmap.recycle();
				srcBitmap = null;
			}
			
			// 提高对比度
			if (bContrast)
			{
				Bitmap tempBitmap = Bitmap.createBitmap(dstBitmap.getWidth(), dstBitmap.getHeight(), Bitmap.Config.ARGB_8888);
				
				Canvas canvas = new Canvas(tempBitmap);
				ColorMatrix cm = new ColorMatrix();
				float contrast = 30.f / 180.f; // 提高30对比度
				setContrast(cm, contrast);
				Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
				paint.setColorFilter(new ColorMatrixColorFilter(cm));
				canvas.drawBitmap(dstBitmap, 0, 0, paint);
				
				if (!dstBitmap.isRecycled()) dstBitmap.recycle();
				dstBitmap = null;
				dstBitmap = tempBitmap;
			}
			// 提高锐化
			if (bSharp)
			{
			}
			// 保存文件
			if (dstFile.exists()) dstFile.delete();
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstFile));
			dstBitmap.compress(CompressFormat.JPEG, 90, bos);
			
			if (!dstBitmap.isRecycled()) dstBitmap.recycle();
			dstBitmap = null;
			
			bos.flush();
			bos.close();
			bRet = true;
		}
		catch (Exception e)
		{
			return bRet;
		}
		
		return bRet;
	}
	
	/**
	 * 设置对比度矩阵
	 */
	private static void setContrast(ColorMatrix cm, float contrast) {
		float scale = contrast + 1.f;
		float translate = (-.5f * scale + .5f) * 255.f;
		cm.set(new float[] {
		        scale,
		        0,
		        0,
		        0,
		        translate,
		        0,
		        scale,
		        0,
		        0,
		        translate,
		        0,
		        0,
		        scale,
		        0,
		        translate,
		        0,
		        0,
		        0,
		        1,
		        0
		});
	}
	
	/**
	 * 获得旋转角度
	 * 
	 * @param rotate
	 * @return
	 */
	private static float getImageRotate(int rotate) {
		float f;
		if (rotate == 6)
		{
			f = 90.0F;
		}
		else if (rotate == 3)
		{
			f = 180.0F;
		}
		else if (rotate == 8)
		{
			f = 270.0F;
		}
		else
		{
			f = 0.0F;
		}
		
		return f;
	}
	
	/**
	 * 获取长宽都不超过160dip的图片，基本思想是设置Options.inSampleSize按比例取得缩略图
	 */
	public static Options getOptionsWithInSampleSize(String filePath, int maxWidth) {
		Options bitmapOptions = new Options();
		bitmapOptions.inJustDecodeBounds = true;// 只取得outHeight(图片原始高度)和
		// outWidth(图片的原始宽度)而不加载图片
		BitmapFactory.decodeFile(filePath, bitmapOptions);
		bitmapOptions.inJustDecodeBounds = false;
		int inSampleSize = bitmapOptions.outWidth / (maxWidth / 10);// 应该直接除160的，但这里出16是为了增加一位数的精度
		if (inSampleSize % 10 != 0)
		{
			inSampleSize += 10;// 尽量取大点图片，否则会模糊
		}
		inSampleSize = inSampleSize / 10;
		if (inSampleSize <= 0)
		{// 判断200是否超过原始图片高度
			inSampleSize = 1;// 如果超过，则不进行缩放
		}
		bitmapOptions.inSampleSize = inSampleSize;
		return bitmapOptions;
	}
	
	/**
	 * 保存位图
	 * 
	 * @param bitmap
	 * @param path
	 * @return
	 */
	public static void saveBitmapForShare(Bitmap bitmap, String path) {
		saveBitmapForShare(bitmap, path, null);
	}
	
	/**
	 * 保存位图
	 * 
	 * @param bitmap
	 * @param path
	 * @return
	 */
	public static void saveBitmapForShare(Bitmap bitmap, String path, CompressFormat format) {
		if (bitmap == null || Utils.isEmpty(path)) return;
		FileOutputStream fileOut = null;
		
		try
		{
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			if (format == null)
			{
				if (path.endsWith(".png"))
				{
					format = CompressFormat.PNG;
				}
				else if (path.endsWith(".jpg") || path.endsWith(".jpeg"))
				{
					format = CompressFormat.JPEG;
				}
				else
				{
					format = CompressFormat.PNG;
				}
			}
			bitmap.compress(format, 100, byteOut);
			byte[] buffer = byteOut.toByteArray();
			
			fileOut = new FileOutputStream(path);
			fileOut.write(buffer, 0, buffer.length);
			fileOut.flush();
		}
		catch (Exception ex)
		{
		}
		finally
		{
			try
			{
				if (fileOut != null) fileOut.close();
			}
			catch (Exception ex)
			{
			}
		}
	}
	
	/**
	 * 将Bitmap保存为本地图片
	 * 
	 * @param bm
	 * @param path
	 *            路径
	 * @param filename
	 *            文件名
	 * @return
	 */
	public static boolean saveBitmap(Bitmap bm, String path, String filename) {
		File dir = new File(path);
		if (!dir.exists())
		{
			dir.mkdir();
		}
		File f = new File(dir, filename);
		try
		{
			f.createNewFile();
			FileOutputStream out = new FileOutputStream(f);
			bm.compress(Bitmap.CompressFormat.PNG, 90, out);
			out.flush();
			out.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public static Map<String, SoftReference<Bitmap>> map = new HashMap<String, SoftReference<Bitmap>>();
	
	public static Drawable getComplieDrawable(Context context, int[] resources) {
		if (resources == null || resources.length == 0) { return null; }
		Bitmap[] bitmaps = new Bitmap[resources.length];
		Resources res = context.getResources();
		for (int i = 0; i < bitmaps.length; i++)
		{
			int id = resources[i];
			SoftReference<Bitmap> reference = map.get(id + "");
			Bitmap bitmap = reference != null ? reference.get() : null;
			bitmaps[i] = bitmap == null ? drawableToBitmap(res.getDrawable(id)) : bitmap;
			if (bitmap == null)
			{
				map.put(id + "", new SoftReference<Bitmap>(bitmaps[i]));
			}
		}
		String ids = "";
		for (int i = 0; i < resources.length; i++)
		{
			ids += resources[i];
		}
		Bitmap createBitmap = null;
		SoftReference<Bitmap> reference = map.get(ids);
		if (reference != null && reference.get() == null)
		{
			createBitmap = reference.get();
		}
		else
		{
			createBitmap = createBitmap(bitmaps);
		}
		Drawable drawable = new BitmapDrawable(res, createBitmap);
		return drawable;
	}
	
	private static Bitmap createBitmap(Bitmap... bitmaps) {
		if (bitmaps == null || bitmaps.length == 0) { return null; }
		int width = bitmaps[0].getWidth();
		int height = bitmaps[0].getHeight();
		int padding = 10;
		Bitmap bitmap = Bitmap.createBitmap((width + padding) * bitmaps.length, height + padding, Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		for (int i = 0; i < bitmaps.length; i++)
		{
			canvas.drawBitmap(bitmaps[i], (width + padding) * i + padding / 2, padding / 2, null);
		}
		canvas.save();
		canvas.restore();
		return bitmap;
	}
	
	public static Bitmap drawableToBitmap(Drawable drawable) {
		if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); }
		
		int width = drawable.getIntrinsicWidth();
		width = width > 0 ? width : 1;
		int height = drawable.getIntrinsicHeight();
		height = height > 0 ? height : 1;
		
		Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
		drawable.draw(canvas);
		
		return bitmap;
	}
}
